/* eslint-disable prettier/prettier */

import { Vector3 } from 'three';
import { camera } from './scene.js';
let k = true;
const forGroupArray = (spriteGroup) => {
  if (k) {
    k = false;
    for (let i = 0; i < spriteGroup.children.length; i++) {
      spriteGroup.children[i].visible = true;
      for (let j = i + 1; j < spriteGroup.children.length; j++) {
        spriteIntersect(spriteGroup.children[i], spriteGroup.children[j]);
      }
    }
    setTimeout(() => {
      k = true;
    }, 1000);
  }
};

const spriteIntersect = (sprite1, sprite2) => {
  const axis1 = tag(sprite1);
  const axis2 = tag(sprite2);
  sprite2.userData.haveInsert = 'test';
  sprite1.userData.haveInsert = 'hide';
  if (
    axis1.x + axis1.width > axis2.x &&
    axis2.x + axis2.width > axis1.x &&
    axis1.y + axis1.height > axis2.y &&
    axis2.y + axis2.height > axis1.y &&
    sprite1.visible &&
    sprite2.visible
  ) {
    const pos1 = sprite1.position;
    const pos2 = sprite2.position;
    const distance1 = pos1.distanceTo(camera.position);
    const distance2 = pos2.distanceTo(camera.position);
    if (distance1 > distance2) {
      sprite1.visible = false;
      sprite1.userData.haveInsert = 'hide';
    } else {
      sprite2.visible = false;
      sprite2.userData.haveInsert = 'hide';
    }
  } else {
    if (sprite1.userData.haveInsert == 'hide') {
      return;
    } else {
      sprite1.visible = true;
      sprite1.userData.haveInsert == 'test';
    }
    if (sprite2.userData.haveInsert == 'hide') {
      return;
    } else {
      sprite2.visible = true;
      sprite1.userData.haveInsert == 'test';
    }
  }
};
const tag = (sprite) => {
  const worldVector = new Vector3(
    sprite.position.x,
    sprite.position.y,
    sprite.position.z
  );
  const standardVector = worldVector.project(camera);
  const winWidth = window.innerWidth;
  const winHeight = window.innerHeight;
  const a = winWidth / 2;
  const b = winHeight / 2;
  const x = Number(Math.round(standardVector.x * a + a)); //标准设备坐标转屏幕坐标
  const y = Number(Math.round(-standardVector.y * b + b)) - 30; //标准设备坐标转屏幕坐标
  const width = 100; // canvas的宽度与高度
  const height = 40;
  return { x, y, width, height };
};

export { forGroupArray };
